define(function(require){
    $(function(){
    	/*---------- 流量分片管理——管理员 ----------*/
    	trafficId = semi.utils.getUrlParam('traffic');
    	
        /* 表格 */
    	var bodyTemplate = ['<tr resource_id="{id}">',
	    	                    '<td class="txtc" start="{start}" end="{end}">{start} 至 {end}</td>',
	    	                    '<td class="txtc">{hours}</td>',
	    	                    '<td class="txtc">{areas}</td>',
	    	                    '<td class="txtc">{state}</td>',
	    	                    '<td class="txtc">{cost}</td>',
		                     	'<td class="txtc">',
		                     		'<a class="ibtn showchart {disabled}" href="javascript:;" title="查看报表"><span class="glyphicon glyphicon-list-alt"></span></a>',
		                     		'<a class="ibtn setbtn {disabled} {material}" href="javascript:;" title="设置默认素材"><span class="glyphicon glyphicon-cog"></span></a>',
		                     		'<a class="ibtn relatedbtn {disabled}" href="javascript:;" title="关联策略"><span class="glyphicon glyphicon-th-list"></span></a>',
	                     		'</td>',
		                     '</tr>'].join('');
        
        var date = $('[name=reservation]').val().split(' 至 ');
        var grid = Grid.init({
	            holder:'recourseList',
	            bodyTemplate:bodyTemplate,
	            dataSource:'/trp/resource/get_resources/',
	            pageTemplate:semi.grid.pageTemplate,
	            sendOnPageSize: true
	        });
        
        grid.modifyModel(function(data){
        	if(data.hours.length==24){
    			data.hours = '全天';
    		}else{
    			data.hours = semi.utils.shorterNums(data.hours).join(',');
    		}
        	var disabled = '';
        	if(data.state==1){
        		data.state = '是';
        		if(data.material!=0){
            		data.material = 'green';
            	}else{
            		data.material = '';
            	}
        	}else{
        		data.state = '否';
        		disabled = 'disabled';
        		data.cost = '<span class="gray">—</span>'
    			data.material = '';
        	}
        	$.extend(data,{
    			disabled: disabled
    		});
    	});
        
        //表格数据-流量开关：active 1开   0关 + 是否可删
        grid.onfilled(function(data){
        	grid.data = data;
        	/*$('#trafficList .delbtn').each(function(){
        		var $this = $(this), can_deleted = $this.attr('can_deleted');
        		if(can_deleted=='false'){
        			$this.addClass('disabled').removeClass('delbtn');
        		}
        	});*/
        	$('#recourseList .setbtn').each(function(){
        		if($(this).hasClass('green')){
        			$(this).attr('title','已设置默认素材');
        		}
        	});
        	if(semi.utils.isEmpty($('#trafficList').data('loaded'))){
        		var tdTmpl = ['<td class="txtc">{position_name}</td>',
        	                    '<td class="txtc">{position_attrs}</td>',
        	                    '<td class="txtc">{width}</td>',
        	                    '<td class="txtc">{height}</td>',
        	                    '<td class="txtc" max="{max}">{max}</td>',
        	                    '<td class="txtc">{media_name}</td>',
        	                    '<td class="txtc">{media_attrs}</td>',
        	                    '<td class="txtc" start="{start}" end="{end}">{start} 至 {end}</td>',
        	                    '<td class="txtc">{pv}</td>',
        	                    '<td class="txtc">{click}</td>',
        	                    '<td class="txtc">{shared}</td>'].join('');
        		
        		tdTmpl = tdTmpl.replaceAll('{position_name}', data.position_name)
        					   .replaceAll('{position_attrs}', data.position_attrs)
							   .replaceAll('{width}', data.width)
							   .replaceAll('{height}', data.height)
							   .replaceAll('{max}', data.max)
							   .replaceAll('{media_name}', data.media_name)
							   .replaceAll('{media_attrs}', data.media_attrs)
							   .replaceAll('{start}', data.start)
							   .replaceAll('{end}', data.end)
							   .replaceAll('{pv}', data.pv)
							   .replaceAll('{click}', data.click)
							   .replaceAll('{shared}', data.shared)
        		$('#trafficList tbody tr').empty().append(tdTmpl);
        		
        		var border = '';
        		$('#trafficList thead th,#trafficList tbody td').each(function(){
        			if($(this).isTag('th')){
        				$(this).css('border-top',border);
        			}else{
        				$(this).css('border-bottom',border);
        			}
        			if(this.scrollWidth > this.clientWidth){
                        $(this).addClass('ellipsis').attr('title', $(this).text());
                    }else{
                    	$(this).removeAttr('title');
                    }
        		});
        		$('#trafficList thead th:first,#trafficList tbody td:first').css('border-left',border);
        		$('#trafficList thead th:last,#trafficList tbody td:last').css('border-right',border);
        		
        		$('#trafficList').data('loaded',true);
        	}
        	$('.ibtn').tooltip();
        });
        
        /* 数据搜索 */
        var filterData = function(pno){
        	var d = $('[name=reservation]').val().split(' 至 '),
        		state = $('[name=state]').val(),
            	pageSize = 20;
        	
        	if($('select.page-size').size()>0){
        		pageSize = $('select.page-size').val();
        	}
            grid.send({
            	traffic: trafficId,
        		start: d[0],
        		end: d[1],
        		state: state,
        		pageSize: pageSize,
        		pageNo: pno || 1
        	});
        };
        filterData();
        
        //按购买周期模糊搜索
        $('input[name=reservation]').daterangepicker({
        	opens: 'left',
            format:'YYYY-MM-DD'
        }, function(start, end, label) {
        	console.log(start.toISOString(), end.toISOString(), label);
        	filterData();
        });
        
        //按是否独占搜索
        $('.pageheader select[name=state]').select2().on('change', function(){
        	filterData();
        });
        
        /* 设置默认素材 */
        var $classify = require('./common/classify');
        $(document).on('click', '.setbtn', function(){
        	var $this = $(this), $tr = $this.parents('tr:first'), resource_id = $tr.attr('resource_id'), data = {resource_ids: [resource_id]}, minSum = parseInt($('#trafficList [max]').attr('max'));
        	if($this.hasClass('disabled'))return;
        	$ajax.ajax({
        		url:'/static/trp/template/classify.html',
        		success: function(html){
        			$dialog({
        	        	title: '设置默认素材',
        	        	content: html,
        	        	onshow: function(){
        	        		$classify.init({
        	        			data: data,
        	        			getgroup: 1
        	        		});
        	        	},
        	        	okValue: '确定',
                    	ok: function(){
                    		var $d = this, $node = $(this.node);
                    			
                    		if(!$classify.check())return false;
                			var dataArr = $classify.get(), mSum = 0;
                    		
                    		$.each(dataArr, function(i,n){
	            				var materials = [];
	            				$.each(n.materials, function(j, m){
	            					materials.push(m.id);
	            					mSum++;
	            				});
	            				n.materials = materials;
	            			});
                    		
                    		if(mSum!=0 && mSum<minSum){
                    			$dialog.alert('分组内素材数 【'+mSum+'】<b>小于</b> 广告位分栏数 【'+minSum+'】，请检查！','warning');
                    			return false;
                    		}
                    		
                    		$ajax.ajax({
                    			url: '/trp/material/set_default_material/',
                    			data: JSON.stringify({resource_id:resource_id, groups:dataArr}),
                        		contentType : "application/json",
                                type : 'POST',
                                dataType : 'json',
                    			success: function(data){
                    				$d.close().remove();
                					$dialog.alert((semi.utils.isEmpty(dataArr)?'清空':'设置')+'默认素材成功！','success');
                					filterData(semi.utils.gridPage(grid));
                    			},
                    			error: function(){
                    				$d.close().remove();
                    				$dialog.alert((semi.utils.isEmpty(dataArr)?'清空':'设置')+'默认素材失败，请稍后重试！','warning');
                    			}
                    		});
                    		return false;
                        },
                        cancelValue: '取消',
                        cancel: function(){}
        	        }).showModal();
        		}
        	});
        });
        
        /* 查看报表-dialog */
        $(document).on('click', '.showchart', function(){
        	if($(this).hasClass('disabled'))return;
        	var $this = $(this), $tr = $this.parents('tr:first'), resource_id = $tr.attr('resource_id');
        	require.async('./common/popchart', function($popchart){
        		$popchart({
                	title: '广告位分片流量报表',
                	btn: $this,
                	dataurl: '/trp/resource/report',
                	type: 'resource',
                	idname: 'resource',
                	idvalue: resource_id
                });
        	});
        });
        
        /* 关联策略 */
        $(document).on('click', '.relatedbtn', function(){
        	if($(this).hasClass('disabled'))return;
    		semi.utils.gotoUrl('/trp/strategy/?resource=' + $(this).parents('tr:first').attr('resource_id'));
        });
        
    });
});